package com.qingke.pms.command.user;

import java.util.ArrayList;
import java.util.List;

import com.qingke.pms.app.ProjectManagementSystemApplication;
import com.qingke.pms.command.UserCommand;
import com.qingke.pms.pojo.Project;
import com.qingke.pms.pojo.ProjectLeader;
import com.qingke.pms.pojo.User;
import com.qingke.pms.util.PMSConsole;

public class IntoProjectCommand extends UserCommand {

	public IntoProjectCommand(User user) {
		super(user);
	}

	@Override
	public void execute() {
		Project project=null;
		while(true){
			String cmd=PMSConsole.promptNotEmpty("choose project by (id,code)>").trim();
			if("id".equalsIgnoreCase(cmd))
				project=id();
			else if("code".equalsIgnoreCase(cmd))
				project=code();
			else{
				PMSConsole.println("err input");
				continue;
			}
			break;
		}
		if(project==null){
			PMSConsole.println("the project is not existed.");
			return ;
		}
		if(dao.isAdminstrator(user)){
			into(project);
		}
		List<ProjectLeader> listPL=dao.selectProjectLeadersByProject(project);
		List<User> listU=new ArrayList<>();
		for(ProjectLeader pl:listPL){
			listU.add(pl.getUser());
		}
		if(listU.contains(user))
			into(project);
		else
			PMSConsole.println("you have no permission to into the project");
	}
	
	private Project id(){
		int id=PMSConsole.getInt("project id:");
		return dao.selectProjectById(id);
	}
	
	private Project code(){
		String code=PMSConsole.promptNotEmpty("project code:");
		return dao.selectProjectByCode(code);
	}
	
	private void into(Project project){
		ProjectManagementSystemApplication.getInstance().setProject(project);
		PMSConsole.println("into project success.");
	}
}
